package com.szaupd.config.job;

import cn.hutool.core.text.UnicodeUtil;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.szaupd.dao.DateRepository;
import com.szaupd.entity.Date;
import com.szaupd.entity.QxData;
import com.szaupd.entity.RankResp;
import com.szaupd.service.QxDataService;
import com.szaupd.utils.IdUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.ResponseEntity;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

@Slf4j
@Component
@EnableScheduling
public class QxDataQueryJob {
    @Resource
    private RestTemplate restTemplate;
    @Resource
    private QxDataService qxDataService;
    @Resource
    private DateRepository dateRepository;
    @Resource
    private IdUtils idUtils;

    @Scheduled(initialDelay = 2000, fixedDelayString = "15000")
    public void job() throws JsonProcessingException {

        //qxDataService.deleteAll();

        Date newDate = dateRepository.findTopByStatusIsOrderByDateAsc(0);
        if (newDate == null) {
            return;
        }
        log.info("最新的未查询日期为" + newDate);

        String[] moveType = {"move_in", "move_out"};  //迁入迁出
        int cityId = 320500;    //城市苏州
        int date = newDate.getDate();    //日期


        String cityRankUrl = "https://huiyan.baidu.com/migration/cityrank.jsonp?dt=city&id=320500&type=MOVETYPE&date=DATE";
        String provinceRankUrl = "https://huiyan.baidu.com/migration/provincerank.jsonp?dt=city&id=320500&type=MOVETYPE&date=DATE";

        try {
            //城市级别
            for (String type : moveType) {
                String url = cityRankUrl.replaceAll("MOVETYPE", type).replaceAll("DATE", date + ""); //url
                ResponseEntity<String> resp = restTemplate.getForEntity(url, String.class, new HashMap<>());    //请求
                String s = UnicodeUtil.toString(resp.getBody());
                String data = s.substring(4, s.length() - 1);
                log.info("data = " + data);
                extracted(date, type, "城市级别", data);                //保存数据
            }

            //省份级别
            for (String type : moveType) {
                String url = provinceRankUrl.replaceAll("MOVETYPE", type).replaceAll("DATE", date + ""); //url
                ResponseEntity<String> resp = restTemplate.getForEntity(url, String.class, new HashMap<>());    //请求
                String s = UnicodeUtil.toString(resp.getBody());
                String data = s.substring(4, s.length() - 1);
                log.info("data = " + data);
                extracted(date, type, "省份级别", data);                //保存数据
            }

            newDate.setStatus(1);
            dateRepository.save(newDate);   //更新日期为1
        } catch (Exception e) {
            newDate.setStatus(2);
            dateRepository.save(newDate);   //更新日期为1
        }
    }

    private void extracted(int date, String type, String level, String data) throws JsonProcessingException {
        ObjectMapper om = new ObjectMapper();
        RankResp rankResp = om.readValue(data, RankResp.class);

        List<RankResp.DataList> list = rankResp.getData().getList();
        List<QxData> qxDataList = new ArrayList<>();
        list.forEach(i -> {
            String name = "";
            if (i.getCity_name() == null) {
                name = i.getProvince_name();
            } else {
                name = i.getCity_name() + "-" + i.getProvince_name();
            }
            QxData qxData = QxData.builder()
                    .id(idUtils.nextId())
                    .direction(type)
                    .date(date)
                    .cityLevel(level)
                    .name(name)
                    .value(i.getValue())
                    .build();
            qxDataList.add(qxData);
        });
        qxDataService.insertList(qxDataList);
    }


}
